package yunjiao.javatutorials.guava.concurrent.spring;

import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

/**
 * 控制器示例
 *
 * @author yangyunjiao
 */
@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
public class DatabaseController {
    private final DatabaseConnectionService dbService;

    private final ConfigReloadService configService;

    @GetMapping("/tables")
    public Map<String, Object> getUsers() {
        try (Connection conn = dbService.getConnection();
             PreparedStatement stmt = conn.prepareStatement("SELECT * FROM INFORMATION_SCHEMA.TABLES");
             ResultSet rs = stmt.executeQuery()) {

            return ResultSetToMapUtil.resultSetToMap(rs);

        } catch (SQLException | InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    @GetMapping("/config/{key}")
    public String getConfig(@PathVariable("key") String key) {
        return configService.getConfig(key, "Not found");
    }

    @GetMapping("/service/status")
    public String getServiceStatus() {
        return String.format("Database Service: %s, Config Service: %s",
                dbService.isRunning() ? "RUNNING" : "STOPPED",
                configService.isRunning() ? "RUNNING" : "STOPPED");
    }
}
